const util = require('../../../utils/util.js')
const domainName = getApp().globalData.domainName
const oss_domain = getApp().globalData.oss_domain
const parameter = getApp().globalData.parameter

const myaudio = wx.createInnerAudioContext()

const user_id = wx.getStorageSync('user_id')
const jg_stu_id = wx.getStorageSync('jg_stu_id')
     
const off_sound = wx.getStorageSync('off_sound')
const off_vibration = wx.getStorageSync('off_vibration')
Page({

  /**
   * 页面的初始数据
   */
  data: { 
    tis : [{ti_id:null}],
    windowHeight:500,
    windowWidth:wx.getSystemInfoSync().windowWidth,
    option_list:['A','B','C'],
    icon_url:oss_domain + 'static/picture/app_icon/',
    current_list_index:0,
    list_show:[],
    ti_bookmarks:[],
    finished:0,
  },

  open_drawer(){this.setData({view_card:true})},
  close_drawer(){this.setData({view_card:false})},
  

  // 设置振动
  set_vibration(e){
    let off_vibration = !e.detail.value
    this.setData({
      off_vibration,
    })
    wx.setStorageSync('off_vibration', off_vibration)
  },

  // 设置音效
  set_sound(e){
    let off_sound = !e.detail.value
    this.setData({
      off_sound
    })
    wx.setStorageSync('off_sound', off_sound)
  },

  // 如果是“随机练习”，则该题做题情况回传服务器
  do_ti_rec(ti_id,select,result){
    // console.log('ti_id',ti_id)
    // console.log('select',select)
    wx.request({
      url: domainName + '/doTi_rec',
      data: {
        jg_stu_id:jg_stu_id || '',
        ti_id:ti_id,
        select:select,
        result:result,
        start_read_time:this.start_read_time,
        select_time:util.formatTime(new Date()),
      },...parameter,
      success: res => {
        // console.log('res.data',res.data)
        if(res.data.row_id){
          console.log('回传成功')
        }else{
          console.log('回传失败')
        }
      },
    })
  },

  // 提交打分
  submit(){
    console.log('提交打分')
    getApp().get_vibration()
    wx.showModal({
      confirmText:'确认提交',
      content: '做对' + this.correct + '题；\n做错' + this.wrong + '题；\n一共做题量为' + (this.correct + this.wrong) + '；\n正确率为' + ((this.correct/(this.correct + this.wrong) || 0)*100).toFixed(1) + '% ！',
      showCancel: true,
      title: '本次战绩如下：',
      success:res=>{
        if(res.confirm){
          wx.showToast({
            title: '提交完成',
            duration: 1500,
            icon: 'success',
            mask: true,
          })
          setTimeout(() => {
            wx.navigateBack()
          }, 1500);

        }
      }
    })
  },

  // 滑动swiper事件
  swiperchange(e){
    // console.log('滑动swiper事件',e)
    let source = e.detail.source
    var current = e.detail.current
    var list_show = this.data.list_show
    if(source=="touch"){
      if(this.admin!=1 && this.disable==1){
        getApp().apply_get_right()
      }
      this.swiperchange_logic(current,list_show)
    }
  },

  swiperchange_logic(current,list_show){
    if(this.data.last_current_index==0 && current==1){
      // console.log('0->1')
      var current_dic = this.ti_list[this.data.current_list_index+2]
      if(current_dic){
        list_show.splice(2,1,current_dic)   // 将索引为2的滑块内容换为题 current_dic
        this.setData({
          current_list_index:this.data.current_list_index + 1,
          list_show:list_show,
          last_current_index:current,
        })
      }else{
        this.go_ti_now(this.ti_list.length-1)
      }
    }else if(this.data.last_current_index==1 && current==2){
      // console.log('1->2')  // 正常的，不用处理
      var current_dic = this.ti_list[this.data.current_list_index+2]
      if(current_dic){
        list_show.splice(0,1,current_dic)  // 将索引为0的滑块内容换为题 current_dic
        this.setData({
          current_list_index:this.data.current_list_index + 1,
          list_show:list_show,
          last_current_index:current,
        })
      }else{
        this.go_ti_now(this.ti_list.length-1)
      }
    }else if(this.data.last_current_index==2 && current == 0){
      // console.log('2->0')
      var current_dic = this.ti_list[this.data.current_list_index+2]
      if(current_dic){
        list_show.splice(1,1,current_dic)  // 将索引为1的滑块内容换为题 current_dic
        this.setData({
          current_list_index:this.data.current_list_index + 1,
          list_show:list_show,
          last_current_index:current,
        })
      }else{
        this.go_ti_now(this.ti_list.length-1)
      }
      /***
       * 以下为后退**/
    }else if(this.data.last_current_index==1 && current == 0){
      // console.log('1->0')
      var current_dic = this.ti_list[this.data.current_list_index-2]
      if(current_dic){
        list_show.splice(2,1,current_dic) // 将索引为2的滑块内容换为题 current_dic
        this.setData({
          list_show:list_show,
          last_current_index:current,
          current_list_index:this.data.current_list_index - 1,
        })
      }else{
        this.go_ti_now(0)
      }
    }else if(this.data.last_current_index==0 && current == 2){
      // console.log('0->2')
      var current_dic = this.ti_list[this.data.current_list_index-2]
      if(current_dic){
        list_show.splice(1,1,current_dic)  // 将索引为1的滑块内容换为题 current_dic
        this.setData({
          list_show:list_show,
          last_current_index:current,
          current_list_index:this.data.current_list_index - 1,
        })
      }else{
        this.go_ti_now(0)
      }
    }else if(this.data.last_current_index==2 && current == 1){
      // console.log('2->1')
      var current_dic = this.ti_list[this.data.current_list_index-2]
      if(current_dic){
        list_show.splice(0,1,current_dic)  // 将索引为0的滑块内容换为题 current_dic
        this.setData({
          current_list_index:this.data.current_list_index - 1,
          list_show:list_show,
          last_current_index:current,
        })
      }else{
        this.go_ti_now(0)
      }
    }
    this.start_read_time = util.formatTime(new Date())
  },

  // 选定习题
  go_ti(e){
    if(this.admin!=1 && this.disable==1){
      getApp().apply_get_right()
    }
    let index = parseInt(e.currentTarget.id)
    this.go_ti_now(index)
  },

  // 前往习题
  go_ti_now(index){
    // console.log('index',index)
    if(index==0){
      this.setData({
        current_index:0,
        list_show:this.ti_list.slice(index,index+2).concat({}),
        last_current_index:0, // 默认最近current==0
      })
    }else if(index==this.ti_list.length-1){
      this.setData({
        current_index:2,
        list_show:[{}].concat(this.ti_list.slice(index-1,this.ti_list.length)),
        last_current_index:2, // 默认最近current==2
      })
    }else{
      this.setData({
        current_index:1,
        list_show:this.ti_list.slice(index-1,index+2),
        last_current_index:1, // 默认最近current==1
      })
    }
    this.start_read_time = util.formatTime(new Date())
    this.setData({
      current_list_index:index,
    })
    
    // 关闭抽屉
    this.close_drawer()
  },

  // 开始选择
  sel(e){
    // console.log('开始选择', e)
    let list_show = this.data.list_show
    let ti_index = e.currentTarget.dataset.ti_index
    // 如果已经选择，则不可重复选择
    if(list_show[ti_index].select){
      return
    }
    let opt_index = e.currentTarget.dataset.opt_index
    let my_select = list_show[ti_index].opt_list[opt_index].no
    let ti_id = list_show[ti_index].ti_id

    // 对比答案，并写入结果
    if(my_select==list_show[ti_index].answer){
      var result = 1  // 正确
      if(!this.data.off_sound){
        // 播放正确音效
        myaudio.src = "/imgs/correct.mp3"
        myaudio.play()
      }
      this.correct += 1
    }else{
      var result = 2  // 错误
      getApp().get_vibration()
      this.wrong += 1
    }

    // 将所选答案写入
    
    list_show[ti_index].selected_opt_index= opt_index
    list_show[ti_index].select= my_select
    list_show[ti_index].result= result
    list_show[ti_index].start_read_time= this.start_read_time
    list_show[ti_index].select_time= util.formatTime(new Date()),
    // 
    this.setData({
      list_show:list_show,
      finished:this.data.finished + 1,
      tis:this.data.tis,
    })

    this.do_ti_rec(ti_id,my_select,result)
  },

    // 收藏题
    set_bookmark(e){
      if(!jg_stu_id){
        wx.showModal({
          content: '在训学员方可收藏习题！',
          title: '提示',
        })
        return
      }
      let ti_id = this.ti_list[this.data.current_list_index].ti_id
      wx.request({
        url: domainName + '/add_bookmarkTi',
        data: {
          ti_id:ti_id,
          jg_stu_id:jg_stu_id,
        },...parameter,
        success: res => {
          getApp().get_vibration()
          let ti_bookmarks = res.data.lis
          this.setData({
            ti_bookmarks:ti_bookmarks
          })
        },
      })
    },
  




  // 渲染习题
  load_ti_list(tis,current_list_index){

    var list_show = tis.slice(0,3)
    this.setData({
      current_list_index:current_list_index,
      list_show:list_show,
    })
    this.start_read_time = util.formatTime(new Date())
    this.ti_list = tis
  },



  // 判断用户做题权限
  page_init(user_id){
    wx.request({
      url: domainName + '/do_ti_init',
      data: {
        user_id:user_id,
      },...parameter,
      success: res => {
        console.log('res',res.data)
        this.admin = res.data.admin
        this.setData({
          ti_bookmarks:res.data.lis,
        })
      },
    })
  },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options',options)
    this.page_init(user_id)

    var tis = JSON.parse(decodeURIComponent(options.tis))  // 要做的习题列表

    this.disable = options.disable
    this.correct = 0
    this.wrong = 0
    this.setData({
      tis,
      off_vibration,
      off_sound,
    })
    // console.log('storage_ti_list',storage_ti_list)

    let current_list_index = 0
    this.setData({
      last_current_index:current_list_index,
    })

    // 渲染习题
    this.load_ti_list(tis,current_list_index)

  },

  onReady(){
    this.setData({
      windowHeight:wx.getSystemInfoSync().windowHeight,
    })
  },

   /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    getApp().get_vibration()
    let  ti_id = this.ti_list[this.data.current_list_index].ti_id
    return {
      // title: this.data.ti_list[this.data.current_list_index].question,
      path: '/pages/doTi/show_ti/show_ti?ti_id=' + ti_id
    }
  },
})